<?php
// +----------------------------------------------------------------------
// | 视频直播
// +----------------------------------------------------------------------
namespace helper\tencent;

class Live
{
    /**
     * @var array|string[]
     */
    private array $config = [
        'appId'    => '',
        'push_cdn' => '',
        'push_key' => '',
        'play_cdn' => '',
        'play_key' => ''
    ];

    public function __construct($config)
    {
        $this->config['appId'] = $config['appId'] ?? '';
        $this->config['push_cdn'] = $config['push_cdn'] ?? '';
        $this->config['push_key'] = $config['push_key'] ?? '';
        $this->config['play_cdn'] = $config['play_cdn'] ?? '';
        $this->config['play_key'] = $config['play_key'] ?? '';
    }

    /**
     * 地址生成器
     * @param string $appName app名称
     * @param string $streamName 直播流名称
     * @param string|null $time 过期时间 sample 2016-11-12 12:00:00
     * @return array
     */
    public function urlBuilder(string $appName = 'AppName', string  $streamName = 'StreamName', string $time = null): array
    {
        $push_cdn = $this->config['push_cdn'];
        $push_key = $this->config['push_key']; //推流主key
        $play_cdn = $this->config['play_cdn'];
        $play_key = $this->config['play_key']; //播流主key

        $push_ext_str = "";
        $play_ext_str = "";
        if ($time) {
            $txTime = strtoupper(base_convert(strtotime($time), 10, 16));
            //txSecret = MD5( KEY + streamName + txTime )
            if ($push_key) {
                $txSecret = md5($push_key . $streamName . $txTime);
                $push_ext_str = "?" . http_build_query(array("txSecret" => $txSecret, "txTime" => $txTime));
            }
            if ($play_key) {
                $txSecret = md5($push_key . $streamName . $txTime);
                $play_ext_str = "?" . http_build_query(array("txSecret" => $txSecret, "txTime" => $txTime));
            }
        }

        // 推流
        $push['rtmp'] = "rtmp://$push_cdn/$appName/$streamName" . $push_ext_str;

        // 播流
        $play = [
            'webrtc' => "webrtc://$play_cdn/$appName/$streamName" . $play_ext_str,
            'flv' => "webrtc://$play_cdn/$appName/$streamName.flv" . $play_ext_str,
            'rtmp' => "rtmp://$play_cdn/$appName/$streamName" . $play_ext_str,
            'm3u8' => "http://$play_cdn/$appName/$streamName.m3u8" . $play_ext_str
        ];

        return [
            'push' => $push['rtmp'],
            'play' => $play['m3u8']
        ];
    }
}